﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerController : MonoBehaviour {

    public int z = 7;
    private int x = 2;

    private Color color1 = new Color(122 / 255f, 85 / 255f, 179 / 255f);
    private Color color2 = new Color(126 / 255f, 93 / 255f, 183 / 255f);

    private Transform m_transform;
    private CameraFollow m_cameraFollow;
    private MapManager m_mapManager;
    private UIManager m_UIManager;
    private UIButton m_pauseButton;

    private bool life = false;
    private bool canPressSpace = true;
    private int gemCount = 0;
    private int scoreCount = 0;

	void Awake () {
        m_transform = GetComponent<Transform>();
        m_cameraFollow = Camera.main.transform.GetComponent<CameraFollow>();
        m_mapManager = GameObject.Find("MapManager").GetComponent<MapManager>();
        m_UIManager = GameObject.Find("UI Root").GetComponent<UIManager>();
        m_pauseButton = GameObject.Find("pause_btn").GetComponent<UIButton>();

        gemCount = PlayerPrefs.GetInt("gem",0);
    }

    private void Start()
    {
        SetPlayerPos();
    }

    void Update () {
        if (life)
        {
            PlayerControl();
        }

        if (Input.GetKeyDown(KeyCode.Space) && canPressSpace && !life)
        {
            m_UIManager.StartGame();
        }
        else if (Input.GetKeyDown(KeyCode.Space) && canPressSpace && life)
        {
            m_UIManager.PauseGame();
        }
	}

    public void Switch()
    {
        if (canPressSpace)
        {
            canPressSpace = false;
        }
        else
        {
            canPressSpace = true;
        }
    }

    public int GetGem()
    {
        return gemCount;
    }

    public void Pay()
    {
        gemCount -= 100;
        PlayerPrefs.SetInt("gem", gemCount);
        m_UIManager.UpdateUI(scoreCount, gemCount);
    }

    /// <summary>
    /// 角色移动控制
    /// </summary>
    private void PlayerControl()
    {
        if (Input.GetKeyDown(KeyCode.A) || Input.GetKeyDown(KeyCode.LeftArrow))
        {
            //left
            if (x != 0)
            {
                z++;
                AddScoreCount();
            }
            if (z % 2 == 1 && x != 0)
            {
                x--;
            }
            SetPlayerPos();
            CalcPosition();
        }

        //right
        if (Input.GetKeyDown(KeyCode.D) || Input.GetKeyDown(KeyCode.RightArrow))
        {
            if (x != 4 || z % 2 == 0)
            {
                z++;
                AddScoreCount();
            }
            if (z % 2 == 0 && x != 4)
            {
                x++;
            }
            SetPlayerPos();
            CalcPosition();
        }
    }


    private void SetPlayerPos()
    {
        Transform playerPos = m_mapManager.mapList[z][x].GetComponent<Transform>();
        MeshRenderer normal_a2 = null;
        
        m_transform.position = playerPos.position + Vector3.up * 0.254f / 2;
        m_transform.rotation = Quaternion.Euler(new Vector3(0,-45,0));

        if (playerPos.tag == "Tile")
        {
            normal_a2 = playerPos.Find("normal_a2").GetComponent<MeshRenderer>();
        }else if(playerPos.tag == "Spikes")
        {
            normal_a2 = playerPos.Find("moving_spikes_a2").GetComponent<MeshRenderer>();
        }else if(playerPos.tag == "SkySpikes")
        {
            normal_a2 = playerPos.Find("smashing_spikes_a2").GetComponent<MeshRenderer>();
        }

        if (normal_a2 != null)
        {
            if (z % 2 == 0)
            {
                normal_a2.material.color = color1;
            }
            else
            {
                normal_a2.material.color = color2;
            }
        }else
        {
            gameObject.AddComponent<Rigidbody>();
            GameOver();
        }
        
    }

    /// <summary>
    /// 生成前方地面
    /// </summary>
    private void CalcPosition()
    {
        if(m_mapManager.mapList.Count - z <= 15)
        {
            m_mapManager.AddPR();
            float offsetZ = m_mapManager.mapList.Count / 2;
            m_mapManager.CreateMapItem(offsetZ);
        }
    }

    private void AddGemCount()
    {
        gemCount++;
        m_UIManager.UpdateUI(scoreCount, gemCount);
    }

    private void AddScoreCount()
    {
        scoreCount++;
        m_UIManager.UpdateUI(scoreCount, gemCount);
    }

    private void OnTriggerEnter(Collider other)
    {
        if(other.tag == "SpikesAttack")
        {
            GameOver();
        }

        if(other.tag == "Gem")
        {
            AddGemCount();
            GameObject.Destroy(other.transform.parent.gameObject);
        }
    }

    private void SaveData()
    {
        PlayerPrefs.SetInt("gem", gemCount);
        if(scoreCount > PlayerPrefs.GetInt("score", 0))
        {
            PlayerPrefs.SetInt("score", scoreCount);
        }
    }

    public void StartGame()
    {
        life = true;
        canPressSpace = true;
        m_cameraFollow.startFollow = true;
        m_mapManager.StartTileDown();
    }

    public void PauseGame()
    {
        life = false;
        canPressSpace = true;
        m_cameraFollow.startFollow = false;
        m_mapManager.StopTileDown();
    }

    public void GameOver()
    {
        if (life)
        {
            SaveData();

            life = false;
            canPressSpace = false;
            m_pauseButton.isEnabled = false;
            m_cameraFollow.startFollow = false;

            m_mapManager.StopTileDown();

            StartCoroutine("ResetGame",2.0f);
        }
        //Time.timeScale = 0;
    }

    private IEnumerator ResetGame(float time)
    {
        yield return new WaitForSeconds(time);
        m_pauseButton.isEnabled = true;
        canPressSpace = true;

        m_UIManager.ResetUI();

        z = 7;
        x = 2;
        scoreCount = 0;

        m_mapManager.ResetMap();

        SetPlayerPos();
        Destroy(this.GetComponent<Rigidbody>());

        m_cameraFollow.transform.position = new Vector3(0.9f, 1.71f, 0.68f);
    }
}
